package com.loopj.ohos.http.sample.services;

import com.loopj.ohos.http.AsyncHttpClient;
import com.loopj.ohos.http.AsyncHttpResponseHandler;
import com.loopj.ohos.http.SyncHttpClient;
import com.loopj.ohos.http.ext.LocalHiLog;
import com.loopj.ohos.http.sample.IntentServiceSample;
import com.loopj.ohos.http.sample.util.IntentUtil;
import cz.msebera.android.httpclient.Header;
import ohos.aafwk.ability.IntentAbility;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.rpc.RemoteException;

import java.util.Locale;

/**
 * ExampleIntentService
 */
public class ExampleIntentService extends IntentAbility {
    /**
     * IntentServiceSample
     */
    public static final String LOG_TAG = "ExampleIntentService:IntentServiceSample";
    /**
     * string
     */
    public static final String INTENT_URL = "INTENT_URL";
    /**
     * string
     */
    public static final String INTENT_STATUS_CODE = "INTENT_STATUS_CODE";
    /**
     * string
     */
    public static final String INTENT_HEADERS = "INTENT_HEADERS";
    /**
     * string
     */
    public static final String INTENT_DATA = "INTENT_DATA";
    /**
     * string
     */
    public static final String INTENT_THROWABLE = "INTENT_THROWABLE";

    private final AsyncHttpClient aClient = new SyncHttpClient();
    /**
     * string
     */
    public ExampleIntentService() {
        super("ExampleIntentService");
    }

    @Override
    public void onStart(Intent intent) {
        LocalHiLog.info(LOG_TAG, "onStart()");
        super.onStart(intent);
    }

    @Override
    protected void onProcessIntent(Intent intent) {
        if (intent != null && intent.hasParameter(INTENT_URL)) {
            aClient.get(this, intent.getStringParam(INTENT_URL), new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    sendBroadcast(new Intent(), IntentServiceSample.ACTION_START);
                    LocalHiLog.info(LOG_TAG, "onProcessIntent onStart");
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    Intent broadcast = new Intent();
                    broadcast.setParam(INTENT_STATUS_CODE, statusCode);
                    broadcast.setParam(INTENT_HEADERS, IntentUtil.serializeHeaders(headers));
                    broadcast.setParam(INTENT_DATA, responseBody);
                    sendBroadcast(broadcast, IntentServiceSample.ACTION_SUCCESS);
                    LocalHiLog.info(LOG_TAG, "onProcessIntent onSuccess");
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Intent broadcast = new Intent();
                    broadcast.setParam(INTENT_STATUS_CODE, statusCode);
                    broadcast.setParam(INTENT_HEADERS, IntentUtil.serializeHeaders(headers));
                    broadcast.setParam(INTENT_DATA, responseBody);
                    broadcast.setParam(INTENT_THROWABLE, error);
                    sendBroadcast(broadcast, IntentServiceSample.ACTION_FAILURE);
                    LocalHiLog.info(LOG_TAG, "onProcessIntent onFailure");
                }

                @Override
                public void onCancel() {
                    sendBroadcast(new Intent(), IntentServiceSample.ACTION_CANCEL);
                    LocalHiLog.info(LOG_TAG, "onProcessIntent onCancel");
                }

                @Override
                public void onRetry(int retryNo) {
                    sendBroadcast(new Intent(), IntentServiceSample.ACTION_RETRY);
                    LocalHiLog.info(LOG_TAG, String.format(Locale.US, "onRetry: %d", retryNo));
                }

                @Override
                public void onFinish() {
                    sendBroadcast(new Intent(), IntentServiceSample.ACTION_FINISH);
                    LocalHiLog.info(LOG_TAG, "onProcessIntent onFinish");
                }
            });
        }
    }

    private void sendBroadcast(Intent intent, String action) {
        LocalHiLog.info(LOG_TAG, "sendBroadcast " + action);
        Operation operation = new Intent.OperationBuilder()
                .withAction(action)
                .build();
        intent.setOperation(operation);
        CommonEventData eventData = new CommonEventData(intent);
        try {
            CommonEventManager.publishCommonEvent(eventData);
        } catch (RemoteException e) {
            LocalHiLog.error(LOG_TAG, e.getMessage());
            LocalHiLog.info(LOG_TAG, e.getMessage());
        }
    }
}
